import { ref, onUnmounted, onMounted } from "vue";
import type { Ref } from "vue";
const useclickoutside = (
  elementRef: Ref<null | HTMLElement>,
  openRef: Ref<boolean>
) => {
  const isclickoutside = ref(false);
  // 事件
  const handler = (e: MouseEvent) => {
    if (elementRef.value) {
      // 元素
      if (elementRef.value.contains(e.target as HTMLElement)) {
        // e.target.classList.contains('modal')
        if (openRef.value === false) {
          console.log("useclickoutside openRef.value = true");
          openRef.value = true;
        }
      } else {
        if (openRef.value) {
          console.log("useclickoutside openRef.value = false");
          openRef.value = false;
        }
      }
    }
  };
  // 例: Dropdown中使用useclickoutside，将代码引入Dropdown中，表示的是Dropdown的生命周期
  onMounted(() => {
    // 监听冒泡阶段的事件
    document.addEventListener("click", handler);
  });
  onUnmounted(() => {
    document.removeEventListener("click", handler);
  });
  return isclickoutside;
};
export default useclickoutside;
